import { Form, Input, InputNumber, message, Modal } from 'antd';

import positionService from '@/api/services/security/positionService';

import { PositionType } from './type';

import { ModalProps } from '#/entity';

export function PositionModal({
  title,
  show,
  formValue,
  onOk,
  onCancel,
}: ModalProps<PositionType>) {
  const [form] = Form.useForm();
  const onFinish = (values: any) => {
    values.order = values.order.toString();
    if (formValue.code) {
      // 存在ID则是修改
      positionService.updatePosition(formValue.code, values).then((res) => {
        if (res > 0) {
          onOk();
          message.success('修改成功');
        }
      });
    } else {
      // 不存在ID则是新增
      positionService.createPosition(values).then((res) => {
        if (res > 0) {
          onOk();
          message.success('新增成功');
        }
      });
    }
  };
  // ______________________________________________________________
  const num = 10000;
  const effectiveFigure = {
    // 校验二维码宽度是否有效
    pattern: /^\d+$/,
    message: '只能输入数字',
  };
  const effectiveFigureNum = {
    validator: (_, value) => {
      if (value > num) {
        return Promise.reject(new Error(`排序数字不能超过${num}`));
      }
      return Promise.resolve();
    },
  };
  const nameWidth = 64;
  const redirectUrlWidth = 128;
  const modalRender = (dom: React.ReactNode) => (
    <Form
      initialValues={formValue}
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      onFinish={onFinish}
      clearOnDestroy
      layout="horizontal"
      // layout="vertical"
    >
      {dom}
    </Form>
  );

  return (
    <Modal
      width={600}
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
      destroyOnClose
      modalRender={modalRender}
    >
      <Form.Item
        name="name"
        label="名称"
        rules={[
          { required: true, message: '请输入横幅名称' },
          {
            validator: (_, value) => {
              if (value.length > nameWidth) {
                return Promise.reject(new Error(`名称长度不能超过${nameWidth}`));
              }
              return Promise.resolve();
            },
          },
        ]}
      >
        <Input showCount maxLength={nameWidth} />
      </Form.Item>
      <Form.Item name="code" label="编码" rules={[{ required: true, message: '请输入编码' }]}>
        <Input disabled={!!formValue.code} showCount maxLength={nameWidth} />
      </Form.Item>
      <Form.Item name="order" label="排序" rules={[{ required: true }]}>
        <InputNumber style={{ width: '100%' }} />
      </Form.Item>
    </Modal>
  );
}
